import urllib.request
import urllib.parse
import json

def create_request(page):
    data = {
        'start': (page-1)*20,
        'limit': 20
    }
    data = urllib.parse.urlencode(data)
    base_url = 'https://m.douban.com/rexxar/api/v2/subject/recent_hot/movie'
    url = base_url + '?' + data

    header = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/139.0.0.0 Safari/537.36',
        'Cookie': 'bid=yw9rll5OvfM; ll="118201"; __utmc=30149280; __utmz=30149280.1757813764.3.3.utmcsr=baidu|utmccn=(organic)|utmcmd=organic; _vwo_uuid_v2=D1CFD0D8D2730FED07EEC00918A408470|1de61df608b2316f02ae53cbd1aa47de; ap_v=0,6.0; __utma=30149280.789360093.1735923832.1757813764.1757838262.4; __utmt_douban=1; __utmb=30149280.1.10.1757838262',
        'accept': 'application/json, text/plain, */*',
        'referer': 'https://movie.douban.com/explore'
    }
    return urllib.request.Request(url=url,headers=header)

def get_content(request):
    response = urllib.request.urlopen(request)
    content = response.read().decode('utf-8')
    return content

def down_load(page,content):
    obj = json.loads(content)
    with open('douban_' + str(page) + '.json', 'w', encoding='utf-8') as fp:
        readable_json = json.dumps(obj, ensure_ascii=False, indent=2)
        fp.write(readable_json)
        fp.write('\n')
        print('第%d页数据写入成功' % page)


if __name__ == '__main__':
    for page in range(1,3):
        request = create_request(page)
        content = get_content(request)
        down_load(page,content)

